package com.example.logprocess.model;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * "[${APP_NAME}:${ServerIP}:${ServerPort}] %d{yyyy-MM-dd HH:mm:ss.SSS} %level ${PID} [%X{traceId}] [%thread] %logger [%line] %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
 */
@Data
@Slf4j
public class LogItem {
    private String appName;
    private String serverIp;
    private int serverPort;
    private String timestamp;
    private String logLevel;
    private int pid;
    private String traceId;
    private String thread;
    private String logger;
    private int line;
    private String message;

    // getters and setters

    public static LogItem parseLogEntry(String data) {
        String regex = "\\[([^:]+):(\\d+\\.\\d+\\.\\d+\\.\\d+):(\\d+)] (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}) (\\w+) (\\d+) \\[([^\\]]*)] \\[([^\\]]*)] (\\S+) \\[(\\d+)] (.+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(data);

        if (matcher.matches()) {
            LogItem logEntry = new LogItem();
            logEntry.setAppName(matcher.group(1));
            logEntry.setServerIp(matcher.group(2));
            logEntry.setServerPort(Integer.parseInt(matcher.group(3)));
            logEntry.setTimestamp(matcher.group(4));
            logEntry.setLogLevel(matcher.group(5));
            logEntry.setPid(Integer.parseInt(matcher.group(6)));
            logEntry.setTraceId(matcher.group(7));
            logEntry.setThread(matcher.group(8));
            logEntry.setLogger(matcher.group(9));
            logEntry.setLine(Integer.parseInt(matcher.group(10)));
            logEntry.setMessage(matcher.group(11));
            return logEntry;
        } else {
            log.info("failed to parse log: {}",data);
//            throw new IllegalArgumentException("Invalid data format");
            return null;
        }
    }
}